<template>
  <div class="safety-stock-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="safety-card">
          <template #header>
            <div class="card-header">
              <h3>动态安全库存计算</h3>
              <el-button-group>
                <el-button type="primary" @click="calculateSafetyStock">计算安全库存</el-button>
                <el-button type="success" @click="exportData">导出数据</el-button>
              </el-button-group>
            </div>
          </template>
          
          <!-- 搜索和过滤区域 -->
          <div class="filter-container">
            <el-form :inline="true" :model="filterForm" class="filter-form">
              <el-form-item label="物料编码">
                <el-input v-model="filterForm.materialCode" placeholder="请输入物料编码" clearable />
              </el-form-item>
              <el-form-item label="物料类型">
                <el-select v-model="filterForm.materialType" placeholder="请选择类型" clearable>
                  <el-option label="原材料" value="raw" />
                  <el-option label="半成品" value="semi" />
                  <el-option label="成品" value="finished" />
                  <el-option label="包装材料" value="packaging" />
                </el-select>
              </el-form-item>
              <el-form-item label="仓库">
                <el-select v-model="filterForm.warehouseId" placeholder="请选择仓库" clearable>
                  <el-option 
                    v-for="warehouse in warehouses" 
                    :key="warehouse.id" 
                    :label="warehouse.name" 
                    :value="warehouse.id" 
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchMaterials">搜索</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 物料安全库存列表 -->
          <el-table
            :data="materialList"
            border
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="materialCode" label="物料编码" width="120" sortable />
            <el-table-column prop="materialName" label="物料名称" width="180" />
            <el-table-column prop="materialType" label="物料类型" width="100">
              <template #default="scope">
                <el-tag>{{ getMaterialTypeLabel(scope.row.materialType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentStock" label="当前库存" width="100" sortable />
            <el-table-column prop="averageDemand" label="平均需求" width="100" sortable />
            <el-table-column prop="leadTime" label="补货周期(天)" width="120" sortable />
            <el-table-column prop="serviceLevel" label="服务水平" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.serviceLevel * 100).toFixed(0) }}%
              </template>
            </el-table-column>
            <el-table-column prop="stdDeviation" label="需求标准差" width="120" sortable />
            <el-table-column prop="safetyStock" label="安全库存" width="100" sortable>
              <template #default="scope">
                <span :class="{ 'stock-warning': scope.row.currentStock < scope.row.safetyStock }">
                  {{ scope.row.safetyStock }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="stockStatus" label="库存状态" width="100">
              <template #default="scope">
                <el-tag :type="getStockStatusType(scope.row)">
                  {{ getStockStatusLabel(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastUpdated" label="最后计算时间" width="160" sortable />
            <el-table-column fixed="right" label="操作" width="160">
              <template #default="scope">
                <el-button link type="primary" @click="viewMaterialDetail(scope.row)">详情</el-button>
                <el-button link type="primary" @click="adjustParameters(scope.row)">调整参数</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="parameters-card">
          <template #header>
            <div class="card-header">
              <h3>计算参数设置</h3>
              <el-button type="primary" @click="saveParameters">保存设置</el-button>
            </div>
          </template>
          
          <el-form :model="calculationParams" label-width="150px">
            <el-form-item label="计算方法">
              <el-radio-group v-model="calculationParams.method">
                <el-radio value="normal" label="正态分布法"></el-radio>
                <el-radio value="poisson" label="泊松分布法"></el-radio>
                <el-radio value="hybrid" label="混合算法"></el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="默认服务水平">
              <el-slider 
                v-model="calculationParams.defaultServiceLevel" 
                :min="80" 
                :max="99.9" 
                :step="0.1" 
                :format-tooltip="formatServiceLevel"
              />
              <div class="param-value">{{ formatServiceLevel(calculationParams.defaultServiceLevel) }}</div>
            </el-form-item>
            
            <el-form-item label="数据周期">
              <el-radio-group v-model="calculationParams.dataPeriod">
                <el-radio value="30" label="近30天"></el-radio>
                <el-radio value="90" label="近90天"></el-radio>
                <el-radio value="180" label="近半年"></el-radio>
                <el-radio value="365" label="近一年"></el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="季节性因素权重">
              <el-rate v-model="calculationParams.seasonalWeight" :max="3" show-score />
            </el-form-item>
            
            <el-form-item label="需求波动敏感度">
              <el-slider 
                v-model="calculationParams.demandSensitivity" 
                :min="0" 
                :max="5" 
                :step="0.5" 
                :format-tooltip="formatSensitivity"
              />
              <div class="param-value">{{ formatSensitivity(calculationParams.demandSensitivity) }}</div>
            </el-form-item>
            
            <el-divider content-position="left">高级选项</el-divider>
            
            <el-form-item label="自动计算频率">
              <el-select v-model="calculationParams.autoCalculateFrequency">
                <el-option label="每天" value="daily" />
                <el-option label="每周" value="weekly" />
                <el-option label="每月" value="monthly" />
                <el-option label="手动" value="manual" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="库存预警阈值">
              <el-input-number 
                v-model="calculationParams.warningThreshold" 
                :min="70" 
                :max="100" 
                :step="5"
                :formatter="(value) => `${value}%`"
                :parser="(value) => value.replace('%', '')"
              />
            </el-form-item>
          </el-form>
          
          <div class="tips-container">
            <h4><el-icon><InfoFilled /></el-icon> 安全库存计算提示</h4>
            <p>安全库存 = Z值 × 需求标准差 × √补货周期</p>
            <p>其中Z值由服务水平决定，例如：</p>
            <ul>
              <li>服务水平95%，Z值=1.645</li>
              <li>服务水平99%，Z值=2.326</li>
              <li>服务水平99.9%，Z值=3.090</li>
            </ul>
            <p>更高的服务水平可以减少缺货风险，但会增加库存成本。</p>
          </div>
        </el-card>
        
        <!-- 趋势图 -->
        <el-card class="trend-card" v-if="selectedMaterials.length === 1">
          <template #header>
            <div class="card-header">
              <h3>{{ selectedMaterials[0].materialName }} 趋势分析</h3>
            </div>
          </template>
          
          <div class="trend-chart">
            <!-- 在实际项目中，这里会使用ECharts等库绘制趋势图 -->
            <div class="chart-placeholder">
              <p>此处将显示所选物料的需求和库存趋势图</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 物料详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="物料库存详情"
      width="70%"
    >
      <div v-if="selectedMaterialDetail" class="material-detail">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="物料编码">{{ selectedMaterialDetail.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="物料名称">{{ selectedMaterialDetail.materialName }}</el-descriptions-item>
          <el-descriptions-item label="物料类型">{{ getMaterialTypeLabel(selectedMaterialDetail.materialType) }}</el-descriptions-item>
          <el-descriptions-item label="当前库存">{{ selectedMaterialDetail.currentStock }}</el-descriptions-item>
          <el-descriptions-item label="安全库存">{{ selectedMaterialDetail.safetyStock }}</el-descriptions-item>
          <el-descriptions-item label="最大库存">{{ selectedMaterialDetail.maxStock }}</el-descriptions-item>
          <el-descriptions-item label="平均日需求">{{ selectedMaterialDetail.averageDemand }}</el-descriptions-item>
          <el-descriptions-item label="需求标准差">{{ selectedMaterialDetail.stdDeviation }}</el-descriptions-item>
          <el-descriptions-item label="服务水平">{{ (selectedMaterialDetail.serviceLevel * 100).toFixed(0) }}%</el-descriptions-item>
          <el-descriptions-item label="补货周期">{{ selectedMaterialDetail.leadTime }} 天</el-descriptions-item>
          <el-descriptions-item label="经济订购批量">{{ selectedMaterialDetail.eoq }}</el-descriptions-item>
          <el-descriptions-item label="最后计算时间">{{ selectedMaterialDetail.lastUpdated }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-chart">
          <h4>近6个月需求与库存趋势</h4>
          <div class="chart-placeholder">
            <p>此处将显示物料的历史需求和库存趋势图</p>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 参数调整对话框 -->
    <el-dialog
      v-model="paramDialogVisible"
      title="调整安全库存参数"
      width="50%"
    >
      <div v-if="selectedMaterialDetail" class="param-adjustment">
        <el-form :model="materialParams" label-width="150px">
          <el-form-item label="物料编码">
            <el-input v-model="materialParams.materialCode" disabled />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="materialParams.materialName" disabled />
          </el-form-item>
          <el-form-item label="服务水平">
            <el-slider 
              v-model="materialParams.serviceLevel" 
              :min="80" 
              :max="99.9" 
              :step="0.1" 
              :format-tooltip="formatServiceLevel"
            />
            <div class="param-value">{{ formatServiceLevel(materialParams.serviceLevel) }}</div>
          </el-form-item>
          <el-form-item label="补货周期(天)">
            <el-input-number v-model="materialParams.leadTime" :min="1" :step="1" />
          </el-form-item>
          <el-form-item label="季节性因素">
            <el-rate v-model="materialParams.seasonalFactor" :max="3" show-score />
          </el-form-item>
          <el-form-item label="手动设置安全库存">
            <el-switch v-model="materialParams.manualSetting" />
          </el-form-item>
          <el-form-item label="安全库存值" v-if="materialParams.manualSetting">
            <el-input-number v-model="materialParams.manualSafetyStock" :min="0" :step="1" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paramDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMaterialParams">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'

export default {
  name: 'SafetyStock',
  components: {
    InfoFilled
  },
  setup() {
    // 状态变量
    const loading = ref(false)
    const detailDialogVisible = ref(false)
    const paramDialogVisible = ref(false)
    const selectedMaterialDetail = ref(null)
    const selectedMaterials = ref([])
    
    // 仓库数据
    const warehouses = ref([
      { id: 'WH001', name: '中央仓库' },
      { id: 'WH002', name: '北区配送中心' },
      { id: 'WH003', name: '南方仓储中心' },
      { id: 'WH004', name: '西部物流中心' }
    ])
    
    // 过滤表单
    const filterForm = reactive({
      materialCode: '',
      materialType: '',
      warehouseId: ''
    })
    
    // 计算参数
    const calculationParams = reactive({
      method: 'normal',
      defaultServiceLevel: 95,
      dataPeriod: '90',
      seasonalWeight: 1,
      demandSensitivity: 2,
      autoCalculateFrequency: 'weekly',
      warningThreshold: 90
    })
    
    // 单个物料参数
    const materialParams = reactive({
      materialCode: '',
      materialName: '',
      serviceLevel: 95,
      leadTime: 7,
      seasonalFactor: 1,
      manualSetting: false,
      manualSafetyStock: 0
    })
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 物料列表数据
    const materialList = ref([])
    
    // 加载物料数据
    const loadMaterialData = () => {
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        // 生成模拟物料数据
        materialList.value = [
          {
            id: 'M001',
            materialCode: 'RAW10001',
            materialName: '铝合金型材',
            materialType: 'raw',
            currentStock: 850,
            averageDemand: 25,
            leadTime: 5,
            serviceLevel: 0.95,
            stdDeviation: 8,
            safetyStock: 75,
            maxStock: 1000,
            eoq: 200,
            lastUpdated: '2024-07-15 09:30:22'
          },
          {
            id: 'M002',
            materialCode: 'RAW20045',
            materialName: '不锈钢板材',
            materialType: 'raw',
            currentStock: 120,
            averageDemand: 15,
            leadTime: 7,
            serviceLevel: 0.98,
            stdDeviation: 5,
            safetyStock: 60,
            maxStock: 200,
            eoq: 100,
            lastUpdated: '2024-07-15 09:30:22'
          },
          {
            id: 'M003',
            materialCode: 'SEMI30012',
            materialName: '主板组件',
            materialType: 'semi',
            currentStock: 250,
            averageDemand: 50,
            leadTime: 3,
            serviceLevel: 0.95,
            stdDeviation: 12,
            safetyStock: 85,
            maxStock: 400,
            eoq: 150,
            lastUpdated: '2024-07-15 09:30:22'
          },
          {
            id: 'M004',
            materialCode: 'FIN40056',
            materialName: '智能控制器',
            materialType: 'finished',
            currentStock: 45,
            averageDemand: 10,
            leadTime: 10,
            serviceLevel: 0.99,
            stdDeviation: 4,
            safetyStock: 50,
            maxStock: 100,
            eoq: 50,
            lastUpdated: '2024-07-15 09:30:22'
          },
          {
            id: 'M005',
            materialCode: 'PKG50023',
            materialName: '包装盒 30x20x15',
            materialType: 'packaging',
            currentStock: 1200,
            averageDemand: 100,
            leadTime: 2,
            serviceLevel: 0.9,
            stdDeviation: 20,
            safetyStock: 120,
            maxStock: 2000,
            eoq: 500,
            lastUpdated: '2024-07-15 09:30:22'
          }
        ]
        
        // 更新总数
        pagination.total = 5
        
        loading.value = false
      }, 500)
    }
    
    // 搜索物料
    const searchMaterials = () => {
      pagination.currentPage = 1
      loadMaterialData()
    }
    
    // 重置筛选条件
    const resetFilter = () => {
      Object.assign(filterForm, {
        materialCode: '',
        materialType: '',
        warehouseId: ''
      })
      searchMaterials()
    }
    
    // 计算安全库存
    const calculateSafetyStock = () => {
      if (selectedMaterials.value.length === 0) {
        ElMessage.warning('请选择至少一个物料进行计算')
        return
      }
      
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(`已为 ${selectedMaterials.value.length} 个物料重新计算安全库存`)
        loadMaterialData()
      }, 1000)
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage.success('安全库存数据已导出')
    }
    
    // 查看物料详情
    const viewMaterialDetail = (material) => {
      selectedMaterialDetail.value = material
      detailDialogVisible.value = true
    }
    
    // 调整参数
    const adjustParameters = (material) => {
      selectedMaterialDetail.value = material
      
      // 填充参数表单
      Object.assign(materialParams, {
        materialCode: material.materialCode,
        materialName: material.materialName,
        serviceLevel: material.serviceLevel * 100,
        leadTime: material.leadTime,
        seasonalFactor: 1,
        manualSetting: false,
        manualSafetyStock: material.safetyStock
      })
      
      paramDialogVisible.value = true
    }
    
    // 保存物料参数
    const saveMaterialParams = () => {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(`物料 ${materialParams.materialName} 的参数已更新`)
        paramDialogVisible.value = false
        loadMaterialData()
      }, 500)
    }
    
    // 保存计算参数
    const saveParameters = () => {
      // 模拟API调用
      ElMessage.success('计算参数设置已保存')
    }
    
    // 格式化服务水平显示
    const formatServiceLevel = (val) => {
      return `${val.toFixed(1)}%`
    }
    
    // 格式化敏感度显示
    const formatSensitivity = (val) => {
      const labels = ['极低', '低', '中低', '中', '中高', '高']
      return labels[val]
    }
    
    // 获取物料类型标签
    const getMaterialTypeLabel = (type) => {
      switch (type) {
        case 'raw':
          return '原材料'
        case 'semi':
          return '半成品'
        case 'finished':
          return '成品'
        case 'packaging':
          return '包装材料'
        default:
          return '未知'
      }
    }
    
    // 获取库存状态类型
    const getStockStatusType = (material) => {
      if (material.currentStock < material.safetyStock) return 'danger'
      if (material.currentStock < material.safetyStock * 1.2) return 'warning'
      if (material.currentStock > material.maxStock) return 'info'
      return 'success'
    }
    
    // 获取库存状态标签
    const getStockStatusLabel = (material) => {
      if (material.currentStock < material.safetyStock) return '库存不足'
      if (material.currentStock < material.safetyStock * 1.2) return '接近预警'
      if (material.currentStock > material.maxStock) return '库存过剩'
      return '正常'
    }
    
    // 选择变更处理
    const handleSelectionChange = (selection) => {
      selectedMaterials.value = selection
    }
    
    // 处理页码变更
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadMaterialData()
    }
    
    // 处理每页条数变更
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadMaterialData()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      loadMaterialData()
    })
    
    return {
      loading,
      warehouses,
      filterForm,
      materialList,
      pagination,
      calculationParams,
      detailDialogVisible,
      paramDialogVisible,
      selectedMaterialDetail,
      materialParams,
      selectedMaterials,
      
      searchMaterials,
      resetFilter,
      calculateSafetyStock,
      exportData,
      viewMaterialDetail,
      adjustParameters,
      saveMaterialParams,
      saveParameters,
      formatServiceLevel,
      formatSensitivity,
      getMaterialTypeLabel,
      getStockStatusType,
      getStockStatusLabel,
      handleSelectionChange,
      handleCurrentChange,
      handleSizeChange
    }
  }
}
</script>

<style>
.safety-stock-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.safety-card {
  margin-bottom: 20px;
}

.parameters-card {
  margin-bottom: 20px;
}

.trend-card {
  height: 320px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.param-value {
  margin-top: 5px;
  text-align: center;
  color: #409EFF;
  font-weight: bold;
}

.tips-container {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.tips-container h4 {
  margin-top: 0;
  color: #409EFF;
  display: flex;
  align-items: center;
  gap: 5px;
}

.tips-container ul {
  padding-left: 20px;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.stock-warning {
  color: #F56C6C;
  font-weight: bold;
}

.material-detail {
  padding: 10px;
}

.detail-chart {
  margin-top: 20px;
}

.detail-chart h4 {
  margin-bottom: 10px;
}

/* 确保下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}
</style> 